function  moments =  simulation_general_belief_results_output( S,   N_years,  output_file_name, yearly_output  )
% Usage:  simulation_results_output( S, N_years, output_file_name )
% This function generate simulation outputs to the output_file_name, which should be an excel file.
if(nargin<2)
    N_years = 10000;
end

if( isfield( S, 'model_sol' ) )
    model_sol = post_processing(S.model_sol);    
else
    model_sol= post_processing(S);
end
par = model_sol.par;  
shocks = shocks_generation( N_years,  par, 1);  
w_init = 0.2;  lambda_init = 0.1;
dB_vec = shocks.dB_vec;
dN_vec = shocks.dN_vec;
sim = simulate_general_belief( w_init, lambda_init,  dB_vec, dN_vec,  N_years, model_sol,  par  );
[ rational_moments,  behavioral_moments ] = simulation_moments( sim, model_sol );

if( par.model_name=="behavioral" )
    moments = behavioral_moments;
else
    moments = rational_moments;
end

if(nargin>=2)
    underlying_lambda = shocks.lambda_MC;
    if( nargin>=4 && yearly_output==true )  % yearly output
        tbl_output = moments.tbl_output(1:12:end,:);
        crisis_vec = zeros( length(tbl_output.T), 1 );
        for( i = 1:length(crisis_vec) )
            crisis_vec(i) = sum(moments.tbl_output.crisis( (12*(i-1)+1):(12*(i-1)+12) ))>0 ; 
        end
        tbl_output = table(  tbl_output.T,  tbl_output.w,   tbl_output.lambda,   tbl_output.lambda_rational,  tbl_output.K,  tbl_output.p,  tbl_output.GDP, tbl_output.productivity  , tbl_output.credit_spread, tbl_output.xK,  tbl_output.dN,    crisis_vec,  tbl_output.rf,  underlying_lambda,   tbl_output.kappap,  ...
                'VariableNames', {   'T',                   'w',                     'lambda',              'lambda_rational',                     'K',                'p',                    'GDP',       'productivity'               , 'credit_spread',                   'xK',         'dN',    'crisis',  'rf', 'underlying_lambda', 'kappap'}   );
    else
        tbl_output = moments.tbl_output;
        tbl_output = addvars(tbl_output,underlying_lambda);    % add the underlying lambda column
    end
    % Then output the table to excel.
    if(nargin>=3) % if a file name is specified
        writetable(  tbl_output , output_file_name ,'Sheet', 1, 'WriteVariableNames',true); 
    end
end
moments.tbl_output = tbl_output;